// 系统管理员服务层
// author: Xavier
package service

import (
	"admin_go_api/api/dao"
	"admin_go_api/api/entity"
	"admin_go_api/common/result"
	"admin_go_api/common/util"
	"admin_go_api/pkg/jwt"
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

// 定义接口
type ISysAdminService interface {
	Login(c *gin.Context, dto entity.LoginDto)
}

type SysAdminServiceImpl struct{}

// 登录
func (s *SysAdminServiceImpl) Login(c *gin.Context, dto entity.LoginDto) {
	// 登录参数校验
	err := validator.New().Struct(dto)
	if err != nil {
		// 校验失败，返回错误信息
		result.Failed(c, int(result.ApiCode.MissingLoginParameter), result.ApiCode.GetMessage(result.ApiCode.MissingLoginParameter))
		return
	}
	// 验证码是否过期
	code := util.RedisStore{}.Get(dto.Idkey, true)
	if code == "" {
		result.Failed(c, int(result.ApiCode.VerificationCodeHasExpired), result.ApiCode.GetMessage(result.ApiCode.VerificationCodeHasExpired))
		return
	}
	// 校验验证码
	verifyRes := CaptVerify(dto.Idkey, dto.Image)
	if !verifyRes {
		result.Failed(c, int(result.ApiCode.CAPTCHAERROR), result.ApiCode.GetMessage(result.ApiCode.CAPTCHAERROR))
		return
	}
	// 校验用户名和密码
	sysAdmin := dao.SysAdminDetail(dto)
	if sysAdmin.Password != util.EncryptionMd5(dto.Password) {
		fmt.Println("输入密码加密后：", util.EncryptionMd5(dto.Password), "数据库密码：", sysAdmin.Password)
		result.Failed(c, int(result.ApiCode.PASSWORDERROR), result.ApiCode.GetMessage(result.ApiCode.PASSWORDERROR))
		return
	}
	const status uint = 2
	if sysAdmin.Status == status {
		fmt.Println("账号状态：", sysAdmin.Status)
		result.Failed(c, int(result.ApiCode.STATUSISENABLE), result.ApiCode.GetMessage(result.ApiCode.STATUSISENABLE))
		return
	}
	// 生成token
	tokenString, err := jwt.GenrateTokenByAdmin(sysAdmin)
	result.Success(c, map[string]interface{}{"token": tokenString, "sysAdmin": sysAdmin})

	// 登录成功，返回token
	result.Success(c, tokenString)
}

var sysAdminService = SysAdminServiceImpl{}

func SysAdminService() ISysAdminService {
	return &sysAdminService
}
